package me.monster.lab.androidrforegroundalive

import android.app.Notification
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.annotation.RequiresApi

/**
 * @description
 * @author: Created jiangjiwei in 2020/11/12 13:37
 */
class MediaProjectionService : Service() {

    companion object {
        private const val TAG = "MediaProjectionService"
        private const val KEY_NOTIFICATION_ID = "NOTIFICATION_ID"
        private const val KEY_NOTIFICATION_STATUS = "NOTIFICATION_STATUS"

        @JvmStatic
        fun start(context: Context, notificationId: Long) {
            val starter = Intent(context, MediaProjectionService::class.java)
            starter.putExtra(KEY_NOTIFICATION_ID, notificationId)
            context.startService(starter)
        }

        @JvmStatic
        fun stop(context: Context) {
            val starter = Intent(context, MediaProjectionService::class.java)
            starter.putExtra(KEY_NOTIFICATION_STATUS, false)
            context.startActivity(starter)
        }
    }

    override fun onCreate() {
        super.onCreate()
        NotificationHelper().init(this)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        intent?.apply {
            val notificationId = getLongExtra(KEY_NOTIFICATION_ID, System.currentTimeMillis())
            val status = getBooleanExtra(KEY_NOTIFICATION_STATUS, true)
            if (status) {
                startForce(notificationId)
            } else {
                stopForeground(true)
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun startForce(notificationId: Long) {
        Log.d(TAG, "---- start force ----")
        val notificationIntent = Intent(this, ScreenCaptureImageActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0)

        val notification: Notification =
            Notification.Builder(this, NotificationHelper.notification_channel_id)
                .setContentTitle("Tittle")
                .setContentText("Content Text")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentIntent(pendingIntent)
                .setTicker("This is Ticker")
                .build()

        startForeground(notificationId.toInt(), notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION)

        Log.d(TAG, "---- end force ----")
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
}